
import csv
from items.ugitems import SongItem
'''
导出csv文件管道
'''
class CsvExportPipeline:

    def __init__(self):
        # item = SongItem()
        # self.ITEM_FIELDS=list((dict(item)).keys()).append('images')
        self.ITEM_FIELDS=['id','song_id','song_name','artist_id','artist_name','type',
                          'album_cover','artist_cover','artist_url','tab_url','images']

    def open_spider(self, spider):
        self.file = open('./temp/csv/artists.csv', 'a', newline='', encoding='utf-8')
        self.writer = csv.DictWriter(self.file,fieldnames=self.ITEM_FIELDS)
        self.writer.writeheader()

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        print('This is csv pipeline. item fields:'+ item.__str__())
        if(isinstance(item, SongItem)):
            self.writer.writerow(item)  
        return item